<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="skuName">
        <el-input
          v-model="queryParams.skuName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="catalogId">
        <categoryCascader @handleChange="queryHandleChange" ref="queryCascader" v-model="queryParams.catalogId" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandId">
        <el-select size="small" v-model="queryParams.brandId" filterable placeholder="请选择">
          <el-option
            v-for="dict in brandList"
            :key="dict.brandId"
            :label="dict.brandName"
            :value="dict.brandId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="skuTitle">
        <el-input
          v-model="queryParams.skuTitle"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number
          v-model="queryParams.beginPrice"
          placeholder="请输入价格"
          clearable
          style="width:200px"
          size="small"
          :min="0"
          @keyup.enter.native="handleQuery"
        />
        <el-input-number
          v-model="queryParams.endPrice"
          placeholder="请输入价格"
          clearable
          style="width:200px;margin-left: 20px"
          :min="0"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall:skuinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mall:skuinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mall:skuinfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['mall:skuinfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="skuInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="skuId" align="center" prop="skuId"/>
      <el-table-column label="spuId" align="center" prop="spuId" v-if="false"/>
      <el-table-column label="商品名称" align="center" prop="skuName" />
      <el-table-column label="所属分类" align="center" prop="catalogName" />
      <el-table-column label="品牌名称" align="center" prop="brandName" />
      <el-table-column label="默认图片" align="center" prop="skuDefaultImg" >
        <template slot-scope="{row}">
          <el-image
            style="width: 50px; height: 50px"
            :src="row.skuDefaultImg"
            fit="fill"
            :preview-src-list="[row.skuDefaultImg]"
          />
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="skuTitle" />
      <el-table-column label="副标题" align="center" prop="skuSubtitle" />
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="销量" align="center" prop="saleCount" />
      <el-table-column label="操作"  width="200" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mall:skuinfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mall:skuinfo:remove']"
          >删除</el-button>
          <el-dropdown
            style="padding-left:8px "
            @command="handleCommand(scope.row,$event)"
            size="small"
            split-button
            type="text">
            <i class="el-icon-s-unfold">更多</i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="uploadImages">上传图片</el-dropdown-item>
              <el-dropdown-item command="seckillSettings">参与秒杀</el-dropdown-item>
              <el-dropdown-item command="reductionSettings">满减设置</el-dropdown-item>
              <el-dropdown-item command="discountSettings">折扣设置</el-dropdown-item>
              <el-dropdown-item command="memberPriceSettings">会员价格</el-dropdown-item>
              <el-dropdown-item command="stockSettings">库存管理</el-dropdown-item>
              <el-dropdown-item command="couponSettings">优惠劵</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" v-if="open" :close-on-click-modal="false" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="spuId" prop="spuId">
              <el-input v-model="form.spuId" placeholder="请输入spuId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="skuName">
              <el-input v-model="form.skuName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="catalogId">
              <categoryCascader v-if="cascaderShow" :size="cascaderSize" @handleChange="handleChange" :cascaderWidth="cascaderWidth" :catelogPath="catalogIds"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brandId">
              <el-select v-model="form.brandId" style="width:370px" filterable placeholder="请选择">
                <el-option
                  v-for="dict in addOrUpdateBrandList"
                  :key="dict.brandId"
                  :label="dict.brandName"
                  :value="dict.brandId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="skuTitle">
              <el-input v-model="form.skuTitle" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副标题" prop="skuSubtitle">
              <el-input v-model="form.skuSubtitle" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销量" prop="saleCount">
              <el-input-number v-model="form.saleCount" :min="0" placeholder="请输入销量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="默认图片">
              <imageUpload :maxCount="1" v-model="form.skuDefaultImg"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品介绍描述">
              <el-input v-model="form.skuDesc" type="textarea" placeholder="请输入商品介绍描述" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--满减设置开始-->
    <el-dialog title="满减设置" v-if="skuFullReductionOpen" :close-on-click-modal="false" :visible.sync="skuFullReductionOpen" append-to-body>
      <el-form>
        <el-form-item label="设置满减">
          <label>满</label>
          <el-input-number
            style="width:160px"
            v-model="skuFullReduction.fullPrice"
            :min="0"
            controls-position="right"
          ></el-input-number>
          <label>元</label>
          <label style="margin-left:15px;">减</label>
          <el-input-number
            style="width:160px"
            v-model="skuFullReduction.reducePrice"
            :min="0"
            controls-position="right"
          ></el-input-number>
          <label>元</label>
          <el-checkbox
            v-model="skuFullReduction.addOther"
            :true-label="1"
            :false-label="0"
          >可叠加优惠</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="skuFullReductionSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!--满减设置结束-->

    <!--折扣设置开始-->
    <el-dialog title="折扣设置" v-if="skuLadderOpen" :close-on-click-modal="false" :visible.sync="skuLadderOpen"append-to-body>
      <el-form>
        <el-form-item label="设置折扣">
          <label>满</label>
          <el-input-number
            style="width:160px"
            :min="0"
            controls-position="right"
            v-model="skuLadder.fullCount"
          ></el-input-number>
          <label>件</label>

          <label style="margin-left:15px;">打</label>
          <el-input-number
            style="width:160px"
            v-model="skuLadder.discount"
            :precision="2"
            :min="0"
            :step="0.01"
            controls-position="right"
          ></el-input-number>
          <label>折</label>
          <el-checkbox
            v-model="skuLadder.addOther"
            :true-label="1"
            :false-label="0"
          >可叠加优惠</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="skuLadderSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!--折扣设置结束-->

    <!--会员价格开始-->
    <el-dialog title="会员价格" v-if="memberPriceOpen" :close-on-click-modal="false" :visible.sync="memberPriceOpen"append-to-body>
      <el-form>
        <el-form-item v-for="(mp,index) in memberPriceList" :key="mp.id">
          {{memberPriceList[index].memberLevelName}}
          <el-input-number
            v-model="memberPriceList[index].memberPrice"
            :precision="2"
            :min="0"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="memberPriceSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!--会员价格结束-->
    <!--图片开始-->
    <el-dialog title="图片" v-if="skuImagesOpen" :close-on-click-modal="false" :visible.sync="skuImagesOpen"append-to-body>
      <ImageUpload v-model="skuImagesList" @handleDeleteImage="handleDeleteImage" :returnType="false"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="skuImagesSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!--图片结束-->
  </div>
</template>

<script>
import { listSkuInfo, getSkuInfo, delSkuInfo, addSkuInfo, updateSkuInfo, exportSkuInfo } from "@/api/mall/pms/skuInfo";
import ImageUpload from '@/components/ImageUpload';
import categoryCascader from '@/views/components/category-cascader';
import {queryListByCatelogId } from "@/api/mall/pms/categoryBrand";
import {queryBrandList} from "@/api/mall/pms/brand";
import {queryMemberPriceBySkuId,batchUpdateMemberPrice} from "@/api/mall/sms/memberPrice";
import {querySkuFullReductionBySkuId,updateSkuFullReduction} from "@/api/mall/sms/skuFullReduction";
import {querySkuLadderBySkuId,updateSkuLadder} from "@/api/mall/sms/skuLadder";
import {querySkuImagesBySkuId,batchAdd} from "@/api/mall/pms/skuImages";
export default {
  name: "SkuInfo",
  components: {
    ImageUpload,
    categoryCascader
  },
  data() {
    return {
      //级联样式
      cascaderShow:false,
      cascaderSize:"medium",
      cascaderWidth:"370px",
	  //按钮loading
	  buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      skuInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      skuFullReductionOpen: false,
      skuLadderOpen: false,
      memberPriceOpen: false,
      skuImagesOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        skuName: undefined,
        skuDesc: undefined,
        catalogId: undefined,
        brandId: undefined,
        skuTitle: undefined,
        skuSubtitle: undefined,
        beginPrice: undefined,
        endPrice: undefined,
        spuId: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        skuId: [
          { required: true, message: "skuId不能为空", trigger: "blur" }
        ],
        spuId: [
          { required: true, message: "spuId不能为空", trigger: "blur" }
        ],
        skuName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        brandId: [
          { required: true, message: "品牌名称不能为空", trigger: "blur" }
        ],
        skuTitle: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        skuSubtitle: [
          { required: true, message: "副标题不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
      },
      //品牌集合
      brandList:[],
      addOrUpdateBrandList:[],
      //分类id
      catalogId:'',
      catalogIds:[],
      //满减信息
      skuFullReduction:{},
      //折扣信息
      skuLadder:{},
      //会员价格
      memberPriceList:[],
      //图片
      skuImagesList:[],
      skuImagesDataList:[],
      skuId:''
    };
  },
  created() {
    this.queryParams.spuId = this.$route.params.id;
    this.getList();
    this.queryBrandList();
  },
  methods: {
    //满减信息
    skuFullReductionSubmit(){
      updateSkuFullReduction(this.skuFullReduction).then(response=>{
        if(response.code==200){
          this.msgSuccess("修改成功");
          this.skuFullReductionOpen=false;
        }
      })
    },
    //折扣信息
    skuLadderSubmit(){
      updateSkuLadder(this.skuLadder).then(response=>{
        if(response.code==200){
          this.msgSuccess("修改成功");
          this.skuLadderOpen=false;
        }
      })
    },
    //会员价格
    memberPriceSubmit(){
      batchUpdateMemberPrice(this.memberPriceList).then(response=>{
        if(response.code==200){
          this.msgSuccess("修改成功");
          this.memberPriceOpen=false;
        }
      })
    },
    //保存图片
    skuImagesSubmit(){
      let imgArr=[];
      let skuImages={};
      if(this.skuImagesDataList.length>0){
        this.skuImagesDataList.forEach(e=>{
          if(e.defaultImg===1){
            skuImages=e;
          }
        })
      }

      if(this.skuImagesList.length>0){
        this.skuImagesList.forEach(e=>{
          let imgParam={
            id:'',
            skuId:this.skuId,
            imgSort:'',
            imgUrl:e,
            defaultImg:0
          }
          imgArr.push(imgParam)
        })
      }
     imgArr.forEach(e=>{
        if(e.imgUrl===skuImages.imgUrl){
          e.defaultImg=1;
        }
      })
      batchAdd(imgArr).then(response=>{
        if(response.code==200){
          this.msgSuccess("保存成功");
          this.skuImagesOpen=false;
        }
      })
    },
    //处理更多指令
    handleCommand(row, command) {
        //库存管理
      if ("stockSettings" == command) {
        this.$router.push("/mall/wareSku/" + row.skuId);
        //满减设置
      }else if("reductionSettings"== command){
        querySkuFullReductionBySkuId(row.skuId).then(response => {
          if(response.code==200&&response.data!=null){
            this.skuFullReductionOpen=true;
            this.skuFullReduction = response.data;
          }else{
            this.msgWarning("未设置");
          }
        }).catch(() => {
        });
        //折扣设置
      }else if("discountSettings"== command){
        querySkuLadderBySkuId(row.skuId).then(response => {
          if(response.code==200&&response.data!=null){
            this.skuLadderOpen=true;
            this.skuLadder = response.data;
          }else{
            this.msgWarning("未设置");
          }
        }).catch(() => {
        });
        //会员价格
      }else if("memberPriceSettings"== command){
        queryMemberPriceBySkuId(row.skuId).then(response => {
          if(response.code==200&&response.data.length>0){
            this.memberPriceOpen=true;
            this.memberPriceList = response.data;
          }else{
            this.msgWarning("未设置");
          }
        }).catch(() => {
        });
        //上传图片
      }else if("uploadImages"== command){
        this.skuImagesList=[];
        this.skuImagesDataList=[];
        querySkuImagesBySkuId(row.skuId).then(response => {
          if(response.code==200){
            this.skuId=row.skuId;
            this.skuImagesOpen=true;
            this.skuImagesDataList=response.data;
            response.data.forEach(e=>{
              this.skuImagesList.push(e.imgUrl)
            })
          }
        }).catch(() => {
        });
      }
    },
    //删除图片
    handleDeleteImage(data){
      this.skuImagesDataList.forEach((item,index)=>{
        if(item.imgUrl===data){
          this.skuImagesDataList.splice(index, 1);
        }
      })
    },
    //选择关联的分类
    handleChange(data){
      this.catalogIds=data;
      this.catalogId=data[data.length-1]
      this.form.brandId=''
      this.addOrUpdateBrandListFn(this.catalogId);
    },
    //品牌列表
    addOrUpdateBrandListFn(catalogId){
      queryListByCatelogId(catalogId).then(response => {
        this.addOrUpdateBrandList = response.data;
      }).catch(() => {
      });
    },

    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      listSkuInfo(this.queryParams).then(response => {
        this.skuInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    //查询
    queryHandleChange(data){
      this.queryParams.catalogId=data[data.length-1];
      this.queryBrandListByCatelogId(this.queryParams.catalogId);
    },
    /** 按分类id查询品牌 */
    queryBrandListByCatelogId(catalogId) {
      this.queryParams.brandId=''
      queryListByCatelogId(catalogId).then(response => {
        this.brandList = response.data;
      }).catch(() => {
      });
    },
    /** 查询品牌 */
    queryBrandList() {
      this.queryParams.brandId=''
      queryBrandList().then(response => {
        this.brandList=[]
        response.data.forEach(e=>{
          let brand = {
            brandId:e.brandId,
            brandName:e.name
          }
          this.brandList.push(brand)
        })
      }).catch(() => {
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        skuId: undefined,
        spuId: undefined,
        skuName: undefined,
        skuDesc: undefined,
        catalogId: undefined,
        brandId: undefined,
        skuDefaultImg: undefined,
        skuTitle: undefined,
        skuSubtitle: undefined,
        price: undefined,
        saleCount: undefined,
      };
      this.catalogIds=[]
      this.addOrUpdateBrandList=[]
      this.cascaderShow=false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.spuId='';
      this.handleQuery();
      this.queryBrandList();
      this.$refs.queryCascader.resetHandle()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.skuId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品管理";
      this.cascaderShow=true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      this.cascaderShow=true;
      const skuId = row.skuId || this.ids
      getSkuInfo(skuId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.catalogIds=response.data.catalogIds;
        this.addOrUpdateBrandListFn(response.data.catalogId)
        this.open = true;
        this.title = "修改商品管理";
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.catalogId=this.catalogIds[this.catalogIds.length-1];
          if(this.form.catalogId===''||this.form.catalogId==null){
            this.msgWarning("所属分类不能为空")
            return false;
          }
          this.buttonLoading = true;
          if (this.form.skuId != null) {
            updateSkuInfo(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(() => {
               this.buttonLoading = false;
            });
          } else {
            addSkuInfo(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const skuIds = row.skuId || this.ids;
      this.$confirm('是否确认删除商品管理编号为"' + skuIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delSkuInfo(skuIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportSkuInfo(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {
          this.exportLoading = false;
        });
    }
  }
};
</script>
